package org.example.config;

import org.apache.commons.collections4.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;

/**
 * 统一处理一样(返回json形式的详细异常)
 */
@RestControllerAdvice
public class GlobalControllerExceptionHandler {
    private  Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(value = { Exception.class })
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String, Object> internalServerError(Exception e) throws IOException {
        logger.error("", e);

        Map<String, Object> map = new HashedMap<>();
        map.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        e.printStackTrace(printWriter);
        map.put("message", stringWriter.toString());
        printWriter.close();
        stringWriter.close();
        return map;
    }

}
